/**
 * 
 */
package de.guidoludwig.jtm.server;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.Search;

/**
 * @author guido
 * 
 */
public class Server {

	private static Server INSTANCE;
	private EntityManagerFactory entityManagerFactory;
	private static String persistenceUnitName = "de.guidoludwig.jtm.domain";

	public static Server getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new Server();
		}
		return INSTANCE;
	}
	
	public static void shutDown() {
		INSTANCE = null;
	}

	private Server() {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		entityManagerFactory = Persistence
				.createEntityManagerFactory(persistenceUnitName);
	}
	
	public void setEntityManagerFactory(EntityManagerFactory factory) {
		entityManagerFactory = factory;
	}

	public EntityManager createEntityManager() {
		return entityManagerFactory.createEntityManager();
	}

	public void reindexLucene() throws InterruptedException {
		EntityManager em = createEntityManager();
		FullTextEntityManager fullTextEntityManager = Search
				.getFullTextEntityManager(em);
		fullTextEntityManager.createIndexer().startAndWait();
		em.close();
	}
	
	public FullTextEntityManager getFullTextEntityManager() {
		EntityManager em = createEntityManager();
		FullTextEntityManager fullTextEntityManager = Search
				.getFullTextEntityManager(em);
		return fullTextEntityManager;
	}
}
